package com.zpark.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.zpark.common.Content;
import com.zpark.common.Path;
import com.zpark.common.R;
import com.zpark.entity.Student;
import com.zpark.service.StudentService;
import com.zpark.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

@WebServlet("/student/*")
public class StudentController extends HttpServlet {
    private StudentService studentService = new StudentServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("------------------------------");
        resp.setContentType("application/json;charset=utf-8");
        // 1. 获取了访问的链接地址
        String pathInfo = req.getPathInfo();
        String methodName = pathInfo.substring(1); // 去掉前导斜杠
        try {
            // 反射的方式：获取当前类的 - methodName的方法
            Method[] methods = this.getClass().getMethods();
            for (Method method : methods) {
                // method 每一个方法
                Path annotation = method.getAnnotation(Path.class);
                if (annotation != null) {
                    String value = annotation.value();
                    if (value.equals(methodName)||value.equals(pathInfo)) {
                        method.invoke(this, req, resp);
                        return;
                    }
                }else{
                    resp.getWriter().write("no path");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write(JSON.toJSONString(R.error("访问失败")));
        }
    }

    // 加一个标识可以让我确认我调用哪个方法 - 注解
    @Path("one")
    public void getOne(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //-----------
        Object attribute = req.getSession().getAttribute(Content.USER_SESSION_KEY);
        System.out.println(attribute);
        //-----------
        String idParam = req.getParameter("id");
        if (idParam == null || idParam.isEmpty()) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing parameter: id");
            return;
        }

        int id = Integer.parseInt(idParam);
        Student student = studentService.getOne(id);
        resp.getWriter().write(JSON.toJSONString(R.ok(student)));
    }


    @Path("list")
    public void getList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String numberParam = req.getParameter("number");
        String sizeParam = req.getParameter("size");
        if (numberParam == null || numberParam.isEmpty() || sizeParam == null || sizeParam.isEmpty()) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing parameters: number or size");
            return;
        }

        int number = Integer.parseInt(numberParam);
        int size = Integer.parseInt(sizeParam);
        List<Student> students = studentService.getPage(size, number);
        resp.getWriter().write(JSONArray.toJSONString(R.ok(students)));
    }


    @Path("add")
    public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String name = req.getParameter("name");
        String ageParam = req.getParameter("age");
        String address = req.getParameter("address");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String statusParam = req.getParameter("status");

        if (username == null || password == null || name == null || ageParam == null || address == null || phone == null || email == null || statusParam == null) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing parameters");
            return;
        }

        int age = Integer.parseInt(ageParam);
        int status = Integer.parseInt(statusParam);

        Student student = new Student();
        student.setUsername(username);
        student.setPassword(password);
        student.setName(name);
        student.setAge(age);
        student.setAddress(address);
        student.setPhone(phone);
        student.setEmail(email);
        student.setStatus(status);

        studentService.add(student);
        resp.getWriter().write(JSONArray.toJSONString(R.ok("添加成功")));

    }

    @Path("edit")
    public void edit(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String idParam = req.getParameter("id");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String name = req.getParameter("name");
        String ageParam = req.getParameter("age");
        String address = req.getParameter("address");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String statusParam = req.getParameter("status");

        if (idParam == null || username == null || password == null || name == null || ageParam == null || address == null || phone == null || email == null || statusParam == null) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing parameters");
            return;
        }

        int id = Integer.parseInt(idParam);
        int age = Integer.parseInt(ageParam);
        int status = Integer.parseInt(statusParam);

        Student student = new Student();
        student.setUsername(username);
        student.setPassword(password);
        student.setName(name);
        student.setAge(age);
        student.setAddress(address);
        student.setPhone(phone);
        student.setEmail(email);
        student.setStatus(status);

        studentService.edit(id, student);
        resp.getWriter().write(JSONArray.toJSONString(R.ok("修改成功")));
    }

    @Path("delete")
    public void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String idParam = req.getParameter("id");
        if (idParam == null || idParam.isEmpty()) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing parameter: id");
            return;
        }

        int id = Integer.parseInt(idParam);
        studentService.remove(id);
        resp.getWriter().write(JSONArray.toJSONString(R.ok("删除成功")));
    }
}
